#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#Author: alvayang <alvayang@tabex.org>
#Last Change: 
#Description: 

import sys
from template import indextmpl
from template import badresourcetmpl
from twisted.web.client import getPage
from twisted.internet.threads import deferToThread
import cjson
import traceback
import urllib2
import urllib

urls = '/index'


def get_resource(url, req):
    try:
        _req = urllib2.Request(url)
        f = urllib2.urlopen(_req)
        z = f.read(4096)
        while z:
            req.write(z)
            z =  f.read(4096)
        req.close()
    except:
        print >> sys.stderr, traceback.format_exc()

class handler:
    def do_GET(self, hreq):
        if hreq.args.has_key('url'):
            url = hreq.args['url'][0]
            deferToThread(get_resource, url, hreq)
            #req = urllib2.Request(url)
            #f = urllib2.urlopen(req)
            #z = f.read(4096)
            #while z:
            #    hreq.write(z)
            #    z =  f.read(4096)
            #hreq.close()
        else:
            x = badresourcetmpl.badresourcetmpl
            self.write(x().respond().encode('utf-8'))
            return

    def do_POST(self, hreq):
        self.do_GET(hreq)


